import os, sys
import StringIO

anoxdataPath = "C:\\Games\\Anachronox\\anoxdata"
mapsPath = os.path.join(anoxdataPath, "MAPS")

if len(sys.path[0]):
    # Executed from the command line.
    outPath = sys.path[0]
else:
    # Executed from some windows thing.
    outPath = os.getcwd()

# Make the output sub-directory.
outPath = os.path.join("entities-dump")
try:
    os.mkdir(outPath)
except OSError:
    pass

from anoxtools import BSP

oldStdOut = sys.stdout
try:
    for filename in os.listdir(mapsPath):
        if not filename.endswith(".bsp"):
            continue
        stream = sys.stdout = StringIO.StringIO()
        f = open(os.path.join(mapsPath, filename), 'rb')
        try:
            reader = BSP.BSPReader(f, "blah")
            reader.DumpEntityLump(f)
        finally:
            f.close()

        f = open(os.path.join(outPath, filename[:-4] +".ent"), "w")
        try:
            f.write(stream.getvalue())
        finally:
            f.close()        
finally:
    sys.stdout = oldStdOut
